﻿using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using AutoMapper.Configuration;
using GiteeApi.Dtos;
using GiteeApi.Models;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using StackExchange.Redis;
using IConfiguration = Microsoft.Extensions.Configuration.IConfiguration;

namespace GiteeApi.Utils
{
    public class JWTUtil
    {
        private readonly IConfiguration _iConfiguration;

        public JWTUtil(IConfiguration iConfiguration)
        {
            _iConfiguration = iConfiguration;
        }

        /// <summary>
        /// JWT 生成
        /// </summary>
        /// <returns></returns>
        public string GetToken(int userId)
        {
            // payload
            var claims = new[]
            {
                new Claim(ClaimTypes.Name, userId.ToString())
            };

            // signiture 数字签名
            var secretByte = Encoding.UTF8.GetBytes(_iConfiguration["Authentication:SecretKey"]);
            var signingKey = new SymmetricSecurityKey(secretByte);
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);

            // 生成 Token
            var Token = new JwtSecurityToken(
                // 发布者
                issuer: _iConfiguration["Authentication:issuer"],
                // 发布对象
                audience: _iConfiguration["Authentication:audience"],
                // payload
                claims,
                // 发布时间
                notBefore: DateTime.UtcNow,
                // 过期时间
                expires: DateTime.UtcNow.AddHours(1),
                // expires: DateTime.UtcNow.AddDays(1),
                // 数字签名
                signingCredentials
            );
            // 转换 Token 到字符串
            return "Bearer " + new JwtSecurityTokenHandler().WriteToken(Token);
        }
    }
}